let Vue;
class VueRouter {
  constructor(options) {
    this.$options = options;
    this.app = new Vue({
      data: {
        current: "/",
      },
    });
    this.routerObj = {};
  }
  init() {
    window.addEventListener("hashchange", this.onHrefChange.bind(this), false);
    this.createComponent();
    this.getRouterArr();
  }
  onHrefChange() {
    this.app.current = window.location.hash.slice(1) || "/";
  }
  getRouterArr() {
    for (let i of this.$options.routes) {
      this.routerObj[i.path] = i;
    }
  }
  createComponent() {
    Vue.component("router-link", {
      props: {
        to: String,
      },
      render(h) {
        return h("a", { attrs: { href: "#" + this.to } }, this.$slots.default);
      },
    });
    Vue.component("router-view", {
      render:(h) => {
        return h(this.routerObj[this.app.current].component);
      },
    });
  }
}

VueRouter.install = function(_Vue) {
  Vue = _Vue;
  Vue.mixin({
    beforeCreate() {
      if (this.$options.router) {
        Vue.prototype.$router = this.$options.router;
        this.$options.router.init()
      }
    },
  });
};

export default VueRouter;
